package com.awccis.common.controller;

import com.awccis.common.pool.CustomerPool;
import com.awccis.common.pool.DriverPool;
import com.awccis.common.service.CommonService;
import com.awccis.common.session.DriverSession;
import com.awccis.common.utils.Constants;
import com.awccis.common.utils.HttpRequestUtil;
import com.awccis.common.model.Message;
import com.awccis.common.utils.JsonUtil;
import com.awccis.common.utils.MD5Utils;
import com.awccis.customer.model.order.OrderBean;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 纯牛奶丶
 * 短信验证接口
 */
@RestController
@RequestMapping(value = "/common", method = RequestMethod.POST)
public class CommonController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Resource
    CommonService commonService;

    /**
     * 接受浏览器发送的电话号码，
     * 并将电话号码发送值nexmo服务器，
     * 并获取返回的request_id和status，
     * 将request_id和请求结果以json数据格式返回给浏览器。
     *
     * @param message {"resetPwdFlag": true, "userType":"driver ","phone": "+8612345678978"}
     * @return {"result": true, "message":""}
     * @throws IOException
     */
    @RequestMapping(value = "/sendPhoneNumber", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object sendPhoneNumber(@RequestBody Message message) throws IOException {
        logger.info("接受发送来的手机号：" + message.toString());
        Map<String, Object> map = new HashMap();

        //预先判断请求是否是要重置密码，是则跳过判断数据库中的手机号，否，则是进行注册请求，执行判断手机号是否存在的请求
        if (!message.isResetPwdFlag()) {
            boolean s = commonService.checkPhoneNumber(message);
            if (s) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "手机号已经注册！");
                return map;
            }
        }else {
            boolean s = commonService.checkPhoneNumber(message);
            if (!s) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "手机号不存在！");
                return map;
            }
        }

        JsonObject json = new JsonObject();
        json.addProperty("api_key", "5537ce1b");
        json.addProperty("api_secret", "OP5kp5agx0xbQuYm");
        json.addProperty("number", message.phone);
        json.addProperty("brand", "Check your AWCCIS ");
        json.addProperty("workflow_id",4);
        String url = Constants.SMS_VERIFICATION_URL;
        String result = HttpRequestUtil.sendPost(url, json.toString(), false);
        //String result = "{\"request_id\":\"I am ok!\",\"status\":\"0\"}";
        logger.info("验证手机号数据：" + result);
        map.put(Constants.MAP_KEY_RESULT, true);
        map.put(Constants.MAP_KEY_MESSAGE, result);
        return map;
    }

    /**
     * 接收浏览器发送的request_id和code，
     * 将request_id和code发送给nexmo服务器，
     * 获取返回的状态码status，
     * 将数据返回给浏览器
     *
     * @param message {"request_id":"********", "code":"****"}
     * @return {"result":true}
     * @throws IOException
     */
    @RequestMapping(value = "/sendCheckInfo", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object sendCheckInfo(@RequestBody Message message) throws IOException {
        logger.info("接受发送验证信息：" + message.toString());

        JsonObject json = new JsonObject();
        json.addProperty("api_key", "5537ce1b");
        json.addProperty("api_secret", "OP5kp5agx0xbQuYm");
        json.addProperty("request_id", message.request_id);
        json.addProperty("code", message.code);
        String url = Constants.SMS_VERIFICATION_CHECK_URL;
        String result = HttpRequestUtil.sendPost(url, json.toString(), false);
        //String result = message.request_id+":"+message.code;
        logger.info("验证code数据：" + result);
        Map<String, Object> map = new HashMap();
        map.put(Constants.MAP_KEY_RESULT, result);
        return map;
    }


    /**
     * 更改密码
     *
     * @param message {"numberType": "customer", "phone": "12345678978", "resetPwd": "123123123"}
     * @return {"result": true} or {"message":"请求值不正确"}
     */
    @RequestMapping(value = "/resetPwd", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object resetPwd(@RequestBody Message message) {
        logger.info("更改密码的数据：" + message.toString());

        Map<String, Object> map = new HashMap();
        String numberType = message.getNumberType();
        boolean result = false;
        String customer = "customer";
        String driver = "driver";
        if (numberType == null || "".equals(numberType)) {
            logger.warn("重置密码请求值非法为空：" + numberType);
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数为空");
            return map;
        }
        if(numberType.equals(customer) || numberType.equals(driver)){
            message.setResetPwd(MD5Utils.MD5(message.getResetPwd()));
            result = commonService.updatePwdByPhone(message);
            map.put(Constants.MAP_KEY_RESULT, true);
            map.put(Constants.MAP_KEY_RESULT, result);
            return map;
        }else{
            logger.warn("重置密码请求值非法：" + numberType);
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求值不正确");
            return map;
        }
    }

    /**
     * 获取当前池子中所有的customer信息
     * @param map {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getCustomerPool", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object getCustomerPool(@RequestBody Map map) throws IOException {
        Map result = new HashMap();
        if(Constants.AWCCIS_CODE.equals(map.get("AWCCIS_CODE").toString())){
            result.put("result",true);
            List list = CustomerPool.getAll();
            logger.error(list.toString());
            result.put("message",list);
        }else{
            result.put("result",false);
        }
        return result;
    }

    /**
     * 获取当前池子中所有的driver信息
     * @param map {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getDriverPool", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object getDriverPool(@RequestBody Map map) throws IOException {
        Map result = new HashMap();

        result.put("req",map);
        result.put("message", DriverPool.getAllOnlineDriver());

        return result;
    }

    /**
     * 删除内存池中错乱的driver
     * @param hashMap {"driverId": 55}
     * @return {}
     */
    @RequestMapping(value = "/deleteDriverFromPool", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map<String,Object> deleteDriverFromPool(@RequestBody HashMap<String, Integer> hashMap){
        logger.info("删除内存中的driver：" + hashMap);
        Map<String, Object> map = new HashMap<>();
        String id = "driverId";
        if(hashMap.get(id) != null){
            int driverId = hashMap.get(id);
            if (DriverPool.isContainById(driverId)){
                boolean result = DriverPool.deleteDriverById(driverId);
                map.put(Constants.MAP_KEY_RESULT, result);
                map.put(Constants.MAP_KEY_MESSAGE, "删除成功！");
            }else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "请求值不存在");
            }
        }else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数异常");
        }
        return map;
    }

    /**
     *
     * 测试
     * @param map
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/addDrivers", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    Object addDrivers(@RequestBody Map map) throws IOException {
        Map result = new HashMap();
        DriverPool.addDriverSession("AAA",new DriverSession(1, "A", "AA", 1, "1", 10, 1, 1, "A", "A", "SUV", 5, 32.2312036415,118.7428951263, true, false,new Date()));
        DriverPool.addDriverSession("BBB",new DriverSession(2, "B", "AA", 2, "2", 10, 1, 1, "B", "B", "SUV", 5, 32.2309177546,118.7348324060, true, false,new Date()));
        DriverPool.addDriverSession("CCC",new DriverSession(3, "C", "AA", 3, "3", 10, 1, 1, "C", "C", "SUV", 5, 32.2244149473,118.7359482050, true, false,new Date()));
        DriverPool.addDriverSession("DDD",new DriverSession(4, "D", "AA", 4, "4", 10, 1, 1, "A", "A", "SUV", 5, 32.2215104411,118.7336307764, true, false,new Date()));
        DriverPool.addDriverSession("EEE",new DriverSession(5, "E", "AA", 5, "5", 10, 1, 1, "A", "A", "SUV", 5, 32.2166907991,118.7252086401, true, false,new Date()));
        DriverPool.addDriverSession("FFF",new DriverSession(6, "F", "AA", 6, "6", 10, 1, 1, "A", "A", "SUV", 5, 32.2125787305,118.7282985449, true, false,new Date()));
        DriverPool.addDriverSession("GGG",new DriverSession(7, "G", "AA", 7, "7", 10, 1, 1, "A", "A", "SUV", 5, 32.2099734164,118.7278693915, true, false,new Date()));
        DriverPool.addDriverSession("HHH",new DriverSession(8, "H", "AA", 8, "8", 10, 1, 1, "A", "A", "SUV", 5, 32.2074860434,118.7217324973, true, false,new Date()));
        DriverPool.addDriverSession("III",new DriverSession(9, "I", "AA", 9, "9", 10, 1, 1, "A", "A", "SUV", 5, 32.2044677437,118.7216359377, true, false,new Date()));
        DriverPool.addDriverSession("JJJ",new DriverSession(10, "J", "AA", 10, "10", 10, 1, 1, "A", "A", "轿车", 5, 32.2024795461,118.7220114470,true,  false,new Date()));
        DriverPool.addDriverSession("KKK",new DriverSession(11, "K", "AA", 11, "11", 10, 1, 1, "A", "A", "轿车", 5, 32.2016987809,118.7218505145,true,  false,new Date()));
        DriverPool.addDriverSession("LLL",new DriverSession(12, "L", "AA", 12, "12", 10, 1, 1, "A", "A", "轿车", 5, 32.1992021028,118.7233954668, true, false,new Date()));
        DriverPool.addDriverSession("MMM",new DriverSession(13, "M", "AA", 13, "13", 10, 1, 1, "A", "A", "轿车", 5, 32.1989842076,118.7198764086, true, false,new Date()));
        DriverPool.addDriverSession("NNN",new DriverSession(14, "N", "AA", 14, "14", 10, 1, 1, "A", "A", "轿车", 5, 32.1875714468,118.7168240547, true, false,new Date()));
        DriverPool.addDriverSession("OOO",new DriverSession(15, "O", "AA", 15, "15", 10, 1, 1, "A", "A", "轿车", 5, 32.1866091780,118.7165343761, true, false,new Date()));
        DriverPool.addDriverSession("PPP",new DriverSession(10061, "P", "AA", 48, "16", 10, 1, 1, "A", "A", "轿车", 5, 32.2369484153,118.7457168102, true, false,new Date()));
        result.put("req",map);
        result.put("message", DriverPool.getAllOnlineDriver());
        return result;
    }
}
